<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="650px" @confirm="handleSubmit"
			@close="handleClose">
			<el-form ref="formRef" :model="formData" label-width="140px" :rules="formRules">
				<!-- <el-form-item label="所属城市" prop="area_id">
					<el-select-v2
						v-model="formData.area_id"
						filterable
						clearable
						:options="optionCity"
						placeholder="请选择"
						class="flex-1"
						:height="280"
					/>
				</el-form-item> -->
				<el-form-item label="分类名称" prop="name">
					<el-input v-model="formData.name" placeholder="请填写分类名称" clearable />
				</el-form-item>
				<el-form-item label="分类图片" prop="icon">
					<div class="w-80">
						<div>
							<material-picker v-model="formData.icon" :limit="1" />
						</div>
						<div class="form-tips">支持扩展名：.jpg .jpeg .png .bmp</div>
					</div>
				</el-form-item>
				<el-form-item label="业务流程" prop="business_stage">
					<table class="dataTable" border="0" cellspacing="0">
						<tbody>
							<tr>
								<th>步骤</th>
								<th>名称</th>
								<th>操作</th>
							</tr>
							<tr v-for="(item,index) in formData.business_stage" :key="'business_stage'+index">
								<td>第{{index+1}}步</td>
								<td>
									<el-input v-model="item.name" placeholder="请输入分类名称" clearable />
								</td>
								<td>
									<el-button type="danger" link @click="deleteBusinessStage(index)">删除</el-button>
								</td>
							</tr>
						</tbody>
					</table>
					<el-button type="primary" link @click="addBusinessStage" style="margin: 0 20px;">添加1行</el-button>
				</el-form-item>
				<el-form-item label="渠道费最高（%）" prop="commission_upper_limit">
					<!-- <el-input v-model="formData.commission_upper_limit" type="number" step="0.01" min="0" max="100" placeholder="请输入分类名称" clearable /> -->
					 <div class="pos">
						<el-input-number v-model="formData.commission_upper_limit" :step="1" :precision="2" :min="0" :max="100" controls-position="right" ></el-input-number>
						<div class="pos-icon">%</div>
					 </div>
					
				</el-form-item>
				<el-form-item label="渠道费最低（元）" prop="commission_lower_limit">
					<el-input v-model="formData.commission_lower_limit" type="number" placeholder="请输入分类名称" clearable />
				</el-form-item>
				<el-form-item label="备注" prop="">
					<el-input v-model="formData.remark" type="textarea" rows="5" placeholder="请填写备注信息" clearable />
				</el-form-item>
				<el-form-item label="启用状态" prop="is_enable" required>
					<el-radio-group v-model="formData.is_enable">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">停用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'
	import { productCateEdit, productCateAdd } from '@/api/product/product';
	import Popup from '@/components/popup/index.vue'
	import { getModulesKey } from '@/router'
	import feedback from '@/utils/feedback'
	import useAppStore from '@/stores/modules/app'
	const useApp = useAppStore()
	const optionCity:any = useApp.optionCity;

	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑分类' : '新增分类'
	})

	const componentsOptions = ref(getModulesKey())
	const querySearch = (queryString : string, cb : any) => {
		const results = queryString
			? componentsOptions.value.filter((item) =>
				item.toLowerCase().includes(queryString.toLowerCase())
			)
			: componentsOptions.value
		cb(results.map((item) => ({ value: item })))
	}
	const formData:any = reactive({
		area_id: '',
		id: '',
		//名称
		name: '',
		icon: '',
		//业务流程
		business_stage: [],
		//备注
		remark: '',
		//启用状态
		is_enable: 1,
		commission_upper_limit: '',
		commission_lower_limit: ''
	})

	const formRules = {
		area_id: [
			{
				required: true,
				message: '请选择所属城市',
				trigger: 'blur'
			}
		],
		name: [
			{
				required: true,
				message: '请输入分类名称',
				trigger: 'blur'
			}
		],
		icon: [
			{
				required: true,
				message: '请上传分类图片',
				trigger: 'blur'
			}
		],
		business_stage: [
			{
				required: true,
				message: '请编辑业务流程',
				trigger: 'blur'
			}
		],
		component: [
			{
				required: true,
				message: '请选择启用状态',
				trigger: 'blur'
			}
		],
		commission_upper_limit: [
			{
				required: true,
				message: '请输入平台服务费上限',
				trigger: 'blur'
			}
		],
		commission_lower_limit: [
			{
				required: true,
				message: '请输入平台服务费下限',
				trigger: 'blur'
			}
		]
	}
	const menuOptions = ref<any[]>([])

	const handleSubmit = async () => {
		// if (Number(formData.commission_lower_limit) >= Number(formData.commission_upper_limit)) {
		// 	feedback.msgError('佣金下限不能大于或等于佣金上限')
		// 	return false
		// }
		if (Number(formData.commission_lower_limit) < 0) {
			feedback.msgError('渠道费最低大于等于零')
			return false
		}
		await formRef.value?.validate()
		let newFormData = JSON.parse(JSON.stringify(formData));
		newFormData.business_stage = JSON.stringify(formData.business_stage.map((item:any,index:any)=>{
			return {name:item.name,step:index+1};
		}));
		newFormData.commission_upper_limit = (Number(newFormData.commission_upper_limit) / 100)
		mode.value == 'edit' ? await productCateEdit(newFormData) : await productCateAdd(newFormData)
		popupRef.value?.close()
		emit('success')
	}

	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}
	
	const addBusinessStage = () => {
		formData.business_stage.push({name:''});
	}
	
	const deleteBusinessStage = (i:any) => {
		formData.business_stage.splice(i,1);
	}

	const setFormData = (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				if (key == 'commission_upper_limit') {
					formData[key] = data[key] * 100
				} else {
					formData[key] = data[key]
				}
				
			}
		}
	}

	const getDetail = async (row : Record<string, any>) => {
		setFormData(row)
	}

	const handleClose = () => {
		emit('close')
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
</script>

<style scoped lang="scss">
	::v-deep .el-input-number{
		width: 100% !important;
		.el-input__inner{
			text-align: left;
		}
		.el-input__inner::after{
			content: '%';
		}
	}
	.pos{
		position: relative;
		width: 100%;
		.pos-icon{
			position: absolute;
			right: 50px;
			top: 0;
			z-index: 999
		}
	}
	// .dataTable {
	// 	width: 80%;
	// 	line-height: 40px;
	// 	text-align: left;
	// 	border-top: 1px solid #eaeaea;
	// 	border-left: 1px solid #eaeaea;
	// 	border-right: 1px solid #eaeaea;

	// 	tr {
	// 		// display: flex;

	// 		th {
	// 			flex: 1;
	// 			height: 40px;
	// 			padding: 0 16px;
	// 			font-weight: 500;
	// 			font-size: 12px;
	// 			color: #999999;
	// 			// background: #f9f8f8;
	// 			border-bottom: 1px solid #eaeaea;
	// 			border-right: 1px solid #eaeaea;
	// 		}

	// 		td {
	// 			flex: 1;
	// 			height: 40px;
	// 			padding: 0 16px;
	// 			font-size: 12px;
	// 			color: #666;
	// 			border-bottom: 1px solid #eaeaea;
	// 			border-right: 1px solid #eaeaea;
	// 		}
	// 	}
	// }
</style>